from flask import Flask, request, jsonify
from PIL import Image
import numpy as np
import io

from Similarity import Similarity

app = Flask(__name__)

similarity = Similarity()


# 定义一个简单的处理函数，这里仅做一个示例
# 你可以根据自己的需求来处理图片并返回一个数字
def process_images(image1, image2):
    # 将图片转换为灰度图并计算简单的图像差异
    image1 = np.array(image1.convert("L"))  # 转为灰度图
    image2 = np.array(image2.convert("L"))

    # 计算两个图片的绝对差异并求和
    diff = np.abs(image1 - image2)
    result = np.sum(diff)

    return float(result)


@app.route("/similarity", methods=["POST"])
def compare_images():
    # 检查请求中是否包含两个文件
    if "image1" not in request.files or "image2" not in request.files:
        return jsonify({"error": "Please provide two image files."}), 400

    # 获取上传的图片
    image1_file = request.files["image1"]
    image2_file = request.files["image2"]

    # 打开图片文件
    image1 = Image.open(io.BytesIO(image1_file.read()))
    image2 = Image.open(io.BytesIO(image2_file.read()))

    global similarity
    result = similarity.flask_interface(image1, image2)

    # 返回结果
    return jsonify({"result": result})


@app.route("/similarity_path", methods=["POST"])
def compare_images_with_path():
    # 检查请求中是否包含两个文件
    if "image_path1" not in request.files or "image_path2" not in request.files:
        return jsonify({"error": "Please provide two image files."}), 400

    # 获取上传的图片
    image1_path = request.files["image1"]
    image2_path = request.files["image2"]

    # 打开图片文件
    # image1 = Image.open(io.BytesIO(image1_file.read()))
    # image2 = Image.open(io.BytesIO(image2_file.read()))

    # 处理图片并计算结果
    global similarity
    result = similarity.flask_interface_path(image1_path, image2_path)

    # 返回结果
    return jsonify({"result": result})


if __name__ == "__main__":
    # app.run(debug=True)
    app.run(host="127.0.0.1", port=8888)
